package com.cn.shuangzi.ad.activity;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.activity.SZSplashActivity;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.R;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.bean.AdShowTypeInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.util.SZDateUtil;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;

import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * Created by CN on 2017-11-28.
 */

public abstract class ADSplashActivity extends SZSplashActivity implements ADManager.OnSplashADLoadListener {
    private long remainTime;
    private Handler handlerAdShow;
    private TTAdNative mTTAdNative;
    private int SPLASH_SHOW_TIME_NORMAL = 3000;
    private int AD_SHOW_TIME = 5000;
    private final int FETCH_DELAY = ADConst.TIME_OUT;
    private long beginTime;
    private List<ADPlatform> adPlatformList;

    private String adType;
    private SZXmlUtil xmlUtil;
    private final String AD_SPLASH = "ad_splash";
    private final String AD_INTERVAL_TIMES = "ad_interval_times";
    private boolean isShowSkipBtnThisTime = true;
    private int adIntervalTimes = 2;
    private View.OnClickListener onVipSkipClickListener;
    private ADPlatform currentAdPlatform;

    @Override
    public void onPreCreated() {
        xmlUtil = new SZXmlUtil(this, AD_SPLASH);
        onPreInitAd();
        initCutDown();
        if (isCanSkipAlways()) {
            isShowSkipBtnThisTime = true;
        } else {
            long time = xmlUtil.getLong(AD_SPLASH);
            if (time == 0) {
                isShowSkipBtnThisTime = false;
            } else {
                boolean isTodayShown = SZDateUtil.isSameDay(new Date(time), new Date());
                isShowSkipBtnThisTime = isTodayShown;
                if (adIntervalTimes > 0) {
                    if (isTodayShown) {
                        int times = xmlUtil.getInt(AD_INTERVAL_TIMES);
                        if (times > adIntervalTimes) {
                            isShowSkipBtnThisTime = false;
                            xmlUtil.put(AD_INTERVAL_TIMES, 1);
                        } else {
                            xmlUtil.put(AD_INTERVAL_TIMES, (++times));
                        }
                    } else {
                        xmlUtil.put(AD_INTERVAL_TIMES, 1);
                    }
                }
            }
        }
    }

    private void initCutDown() {
        txtSkip.setVisibility(View.GONE);
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanSkipAd()) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put(ADConst.AD_SPLASH_SHOW_TIME, String.valueOf((AD_SHOW_TIME - remainTime) / 1000));
                    map.put(ADConst.AD_PLATFORM_KEY, adType);
                    SZManager.getInstance().onUMEvent(ADConst.AD_CLICK_SKIP_EVENT_ID, map);
                    toMain();
                }
            }
        });
    }


    public void fetchSelfAD() {
        fetchSelfAD(null);
    }

    public void fetchSelfAD(ADManager.OnSplashADLoadListener onSplashADLoadListener) {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), onSplashADLoadListener);
    }

    public void fetchSelfADToHome() {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), this);
    }

    public void fetchSplashAD() {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSplash(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), this);
    }

    private void fetchTTSplashAD() {
        int height;
        int width;
        try {
            width = SZUtil.getScreenWidth(this);
            height = splash_container.getHeight();
//            height = SZUtil.getScreenHeight(this);
        } catch (Exception e) {
            height = 0;
            width = 0;
        }
        SZUtil.log("===============拉取穿山甲=================");
        mTTAdNative = TTAdManagerHolder.getInstance().createAdNative(this);
        //开屏广告参数
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(SZUtil.getTT_SPLASH_ID(this))
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width == 0 ? 1080 : width, height == 0 ? 1920 : height)
                .build();
        //调用开屏广告异步请求接口
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            public void onError(int code, String message) {
                SZUtil.log("穿山甲onError:" + message);
                SZManager.getInstance().onUMEvent(ADConst.AD_THIRD_PLATFORM_ERROR_EVENT_ID,
                        ADManager.getInstance().getErrorEventMap(ADConst.AD_PLATFORM_TT,
                                String.valueOf(code), message));
                fetchNextPlatformAd();
            }

            @Override
            public void onTimeout() {
                fetchNextPlatformAd();
            }

            @Override
            public void onSplashAdLoad(TTSplashAd ad) {
                SZUtil.log("=======穿山甲成功======:" + ad);
                if (ad == null) {
                    fetchNextPlatformAd();
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();

                splash_container.removeAllViews();
                //把SplashView 添加到ViewGroup中
                splash_container.addView(view);
                //设置不开启开屏广告倒计时功能以及不显示跳过按钮
//                if(!isCanSkipAd()) {
                ad.setNotAllowSdkCountdown();
//                }
                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
                        SZUtil.log("=====头条广告点击=====");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
                        SZUtil.log("=====头条广告展示=====");
                        if (adType == null) {
                            adType = ADConst.AD_PLATFORM_TT;
                            ADManager.getInstance().setAdShownCompany(ADConst.AD_PLATFORM_TT);
                            SZManager.getInstance().onUMEvent(ADConst.AD_SPLASH_EXPOSURE_EVENT_ID, ADConst.AD_PLATFORM_TT);
                            showCutDown();
                        }
                    }

                    @Override
                    public void onAdSkip() {
                        SZUtil.log("=======穿山甲onAdSkip======");
                        next();
                    }

                    @Override
                    public void onAdTimeOver() {
                        SZUtil.log("=======穿山甲onAdTimeOver======");

                        if (!isShowAdTime()) {
                            next();
                        }
//                        toMain();
                    }
                });
            }
        }, FETCH_DELAY);
    }

    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     */
    private void fetchGDTSplashAD() {
        SZUtil.log("==========拉取广点通=========");
//        String appId = SZUtil.getGDT_APPID(this);
        String posId = SZUtil.getGDT_SPLASH_ID(this);
        new SplashAD(this, rltSkip, posId, new SplashADListener() {
            @Override
            public void onADDismissed() {
            }

            @Override
            public void onNoAD(AdError adError) {
                SZUtil.log("广点通Error|Code:" + adError.getErrorCode() + "|Msg:" + adError.getErrorMsg());
                SZManager.getInstance().onUMEvent(ADConst.AD_THIRD_PLATFORM_ERROR_EVENT_ID,
                        ADManager.getInstance().getErrorEventMap(ADConst.AD_PLATFORM_GDT,
                                String.valueOf(adError.getErrorCode()), adError.getErrorMsg()));
                fetchNextPlatformAd();
            }

            @Override
            public void onADPresent() {
                if (adType == null) {
                    adType = ADConst.AD_PLATFORM_GDT;
                    ADManager.getInstance().setAdShownCompany(ADConst.AD_PLATFORM_GDT);
                    showCutDown();
                }
            }

            @Override
            public void onADClicked() {
            }

            @Override
            public void onADTick(long l) {
            }

            @Override
            public void onADExposure() {

                if (!isShowAdTime()) {
                    next();
                }
                SZManager.getInstance().onUMEvent(ADConst.AD_SPLASH_EXPOSURE_EVENT_ID, ADConst.AD_PLATFORM_GDT);
                SZUtil.log("=====广点通广告展示=====");
            }

            @Override
            public void onADLoaded(long l) {
                SZUtil.log("广点通广告onADLoaded:"+l);

            }
        }, 0).fetchAndShowIn((ViewGroup) findViewById(R.id.splash_container));
    }

    private boolean isShowAdTime() {
        if (currentAdPlatform == null || currentAdPlatform.getAdShowTypeInfo() == null || currentAdPlatform.getAdShowTypeInfo().getLastSecond() <= 0) {
            return false;
        }
        return true;
    }

    private void showCutDown() {
        if (isShowVipSkipBtn()) {
            txtVipSkip.setVisibility(View.VISIBLE);
            if (onVipSkipClickListener == null) {
                txtVipSkip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            startActivity(getVipActivity());
                        } catch (Exception e) {
                        }
                    }
                });
            } else {
                txtVipSkip.setOnClickListener(onVipSkipClickListener);
            }
        } else {
            txtVipSkip.setVisibility(View.GONE);
        }
        if (handlerAdShow != null) {
            handlerAdShow.removeCallbacksAndMessages(null);
        }
        if (handlerAdShow == null) {
            handlerAdShow = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case 200:
                            if (isShowAdTime()) {
                                remainTime -= 1000;
                                if (remainTime <= 0) {
                                    remainTime = 0;
                                }
                                txtSkip.setText(getSkipText());
                                if (remainTime == 0) {
                                    next();
                                } else {
                                    handlerAdShow.sendEmptyMessageDelayed(200, 1000);
                                }
                            }
                            break;
                    }
                }
            };
        }
        txtSkip.setVisibility(View.VISIBLE);
        long timeShow = getAdShowTimeUserDefine() <= 0 ? AD_SHOW_TIME : getAdShowTimeUserDefine();
        remainTime = isCanSkipAd() ? timeShow : AD_SHOW_TIME;
        txtSkip.setText(getSkipText());
        handlerAdShow.sendEmptyMessageDelayed(200, 1000);
        xmlUtil.put(AD_SPLASH, System.currentTimeMillis());
    }

    private boolean isCanSkipAd() {
        if (isCanSkipAlways()) {
            return true;
        }
        return isShowSkipBtnThisTime;
    }

    private String getSkipText() {
        if (isCanSkipAd() && !isShowAdTime()) {
            return getString(R.string.txt_skip);
        }
        return isCanSkipAd() ? (getString(R.string.txt_skip) + " " + remainTime / 1000) : String.valueOf(remainTime / 1000);
    }

    private void toMainByDelay() {
        long delay = getDelayFinishTime();
        toMain(delay);
    }

    private long getDelayFinishTime() {
        long errorTime = System.currentTimeMillis();
        long remainderTime = SPLASH_SHOW_TIME_NORMAL - (errorTime - beginTime);
        return remainderTime > 0 ? remainderTime : 0;
    }

    @Override
    public void onFetchAdSuccess(List<ADPlatform> adPlatformList) {
        SZUtil.log("adPlatformList:" + adPlatformList);
        this.adPlatformList = adPlatformList;
        if (adPlatformList != null && adPlatformList.size() > 0) {
            try {
                ADPlatform adPlatform = adPlatformList.get(ADConst.LOAD_AD_INDEX);
                if (adPlatform.isAdIsOpen()) {
                    fetchPlatformAd(adPlatform);
                } else {
                    toMainByDelay();
                }
            } catch (Exception e) {
                e.printStackTrace();
                toMainByDelay();
            }
        } else {
            toMainByDelay();
        }
    }

    private void fetchNextPlatformAd() {
        if (adPlatformList != null && adPlatformList.size() > 0) {
            fetchPlatformAd(adPlatformList.get(0));
        } else {
            toMainByDelay();
        }
    }

    private void fetchPlatformAd(ADPlatform adPlatform) {
        if (adPlatform != null) {
            this.currentAdPlatform = adPlatform;
            if (adPlatform.getAdShowTypeInfo() != null) {
                if (adPlatform.getAdShowTypeInfo().getLastSecond() > 0) {
                    AD_SHOW_TIME = adPlatform.getAdShowTypeInfo().getLastSecond();
                } else {
                    AD_SHOW_TIME = Integer.MAX_VALUE;
                }
            }
            adPlatformList.remove(adPlatform);
            switch (adPlatform.getAdSupportType()) {
                case ADConst.AD_PLATFORM_TT:
                    fetchTTSplashAD();
                    break;
                case ADConst.AD_PLATFORM_GDT:
                    fetchGDTSplashAD();
                    break;
                default:
                    toMainByDelay();
            }
        } else {
            toMainByDelay();
        }
    }

    @Override
    public void onFetchAdError() {
        toMainByDelay();
    }

    public long getAdShowTimeUserDefine() {
        return 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handlerAdShow != null) {
            handlerAdShow.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public boolean isShowTitleInit() {
        return false;
    }

    public void setSplashShowTime(int splash_show_time_normal) {
        this.SPLASH_SHOW_TIME_NORMAL = splash_show_time_normal;
    }

    public void setADShowTime(int ad_show_time) {
        this.AD_SHOW_TIME = ad_show_time;
    }

    public int getAdIntervalTimes() {
        return adIntervalTimes;
    }

    public void setAdIntervalTimes(int adIntervalTimes) {
        this.adIntervalTimes = adIntervalTimes;
    }

    public View.OnClickListener getOnVipSkipClickListener() {
        return onVipSkipClickListener;
    }

    public void setOnVipSkipClickListener(View.OnClickListener onVipSkipClickListener) {
        this.onVipSkipClickListener = onVipSkipClickListener;
    }

    public void onPreInitAd(){};

    public abstract void onCreated();

    public abstract int getSplashRes();

    public abstract int getAppIconRes();

    public abstract int getAppNameRes();

    public abstract int getAppNameColorRes();

    public abstract Class getHomeActivity();

    public boolean isCanSkipAlways() {
        return true;
    }

    public abstract boolean isShowVipSkipBtn();

    public abstract Class<?> getVipActivity();

}

